package com.yuke.cloud.service.wmc.controller.frontend;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.uac.dto.GroupInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.wmc.dto.WmsFreightInfo;
import com.yuke.cloud.service.wmc.entity.LmsExpress;
import com.yuke.cloud.service.wmc.entity.WmsTransPrice;
import com.yuke.cloud.service.wmc.entity.WmsWarehouse;
import com.yuke.cloud.service.wmc.entity.WmsWarehouseShop;
import com.yuke.cloud.service.wmc.service.LmsExpressService;
import com.yuke.cloud.service.wmc.service.WmsTransPriceService;
import com.yuke.cloud.service.wmc.service.WmsWarehouseService;
import com.yuke.cloud.service.wmc.service.WmsWarehouseShopService;
import com.yuke.cloud.service.wmc.util.DistancdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zys on 2018/12/14.
 */
@Api(value = "WEB - LmsExpressController", tags = "处理LmsExpress相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/lms/express")
public class LmsExpressController extends BaseController {
    @Resource
    private LmsExpressService lmsExpressService;
    @Resource
    private WmsWarehouseShopService wmsWarehouseShopService;
    @Resource
    private WmsWarehouseService wmsWarehouseService;
    @Resource
    private WmsTransPriceService wmsTransPriceService;
    @Resource
    private UacUserFeignApi uacUserFeignApi;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "lmsExpress", value = "该数据记录的POJO") @RequestBody LmsExpress lmsExpress) {
        if (lmsExpress.getIsDefault() != null && !lmsExpress.getIsDefault().equals("")) {
            Boolean isDefault = lmsExpress.getIsDefault();
            if (isDefault) {
                Byte expressType = lmsExpress.getExpressType();
                Example example = new Example(LmsExpress.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("expressType", expressType);
                if (lmsExpress.getWarehouseId() != null) {
                    criteria.andEqualTo("warehouseId", lmsExpress.getWarehouseId());
                }
                List<LmsExpress> lmsExpresses = lmsExpressService.selectByExample(example);
                for (int i = 0; i < lmsExpresses.size(); i++) {
                    lmsExpresses.get(i).setIsDefault(false);
                    lmsExpressService.update(lmsExpresses.get(i));
                }
            }

            lmsExpressService.save(lmsExpress);
        }

        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        lmsExpressService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "lmsExpress", value = "需要修改的内容") @RequestBody LmsExpress lmsExpress) {
        if (lmsExpress.getIsDefault() != null && !lmsExpress.getIsDefault().equals("")) {
            Boolean isDefault = lmsExpress.getIsDefault();
            if (isDefault) {
                Byte expressType = lmsExpress.getExpressType();
                Example example = new Example(LmsExpress.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("expressType", expressType);
                if (lmsExpress.getWarehouseId() != null) {
                    criteria.andEqualTo("warehouseId", lmsExpress.getWarehouseId());
                }
                List<LmsExpress> lmsExpresses = lmsExpressService.selectByExample(example);
                for (int i = 0; i < lmsExpresses.size(); i++) {
                    lmsExpresses.get(i).setIsDefault(false);
                    lmsExpressService.update(lmsExpresses.get(i));
                }
//                lmsExpressService.update(lmsExpress);  // del by wg 20190718
            }
        }
        lmsExpressService.update(lmsExpress);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<LmsExpress> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        LmsExpress lmsExpress = lmsExpressService.findById(id);

        WmsWarehouse wmsWarehouse = wmsWarehouseService.findById(lmsExpress.getWarehouseId());
        lmsExpress.setWarehouseName(wmsWarehouse.getWarehouseName());

        return WrapMapper.ok(lmsExpress);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<LmsExpress>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                              @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                              @RequestParam(required = false) String expressName,
                                              @RequestParam(required = false) Long warehouseId) {
        PageHelper.startPage(page, size);
        Long groupId = getLoginAuthDto().getGroupId();
        //获得groupId
        Wrapper<GroupInfoDto> groupInfoDto = uacUserFeignApi.getGroupInfoByGroupId(groupId);
        if (groupInfoDto.getCode()==200){
            // 登录人为3级部门
            if (groupInfoDto.getResult().getLevel().toString().equals("3")){
                groupId = groupInfoDto.getResult().getParentId();
            }
        }
        System.out.println(groupId);
        List<LmsExpress> lmsExpresses = lmsExpressService.getAllExpress(groupId,warehouseId, expressName);
        PageInfo pageInfo = new PageInfo(lmsExpresses);
        return WrapMapper.ok(pageInfo);
    }


    @GetMapping("/ifunique")
    @ApiOperation(httpMethod = "GET", value = "判断名字是否唯一")
    public Wrapper list(@RequestParam(required = false) String expressName,
                        @RequestParam(value = "expressId", required = false) Long expressId,
                        @RequestParam(value = "warehouseId", required = false) Long warehouseId
    ) {
        Example example = new Example(LmsExpress.class);
        Example.Criteria criteria = example.createCriteria();
        if (expressId != null && !expressId.equals("")) {
            criteria.andNotEqualTo("expressId", expressId);
        }

        if (warehouseId != null && !warehouseId.equals("")) {
            criteria.andEqualTo("warehouseId", warehouseId);
        }

        criteria.andEqualTo("expressName", expressName);
        List<LmsExpress> lmsExpresses = lmsExpressService.selectByExample(example);
        if (lmsExpresses.size() == 0) {
            return WrapMapper.ok("yes");
        } else {
            return WrapMapper.ok("no");
        }

    }

    //批量删除
    @PostMapping("/batchdelete")
    public Wrapper batchdelete(@RequestBody JSONObject jsonObject) {
        String ids = jsonObject.get("ids").toString();
        String[] split = ids.split(",");
        List<LmsExpress> list = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            LmsExpress lmsExpress = new LmsExpress();
            lmsExpress.setExpressId(Long.valueOf(split[i]));
            list.add(lmsExpress);
        }
        int i = lmsExpressService.batchDelete(list);
        if (i == split.length) {
            return WrapMapper.ok("删除成功");
        } else {
            return WrapMapper.ok("删除失败");
        }

    }

    //计算运费价格
    @GetMapping("/countfreight")
    public Wrapper getprice(@RequestParam Long provinceId,
                            @RequestParam Long cityId,
                            @RequestParam Long shopId,
                            @RequestParam Integer weight,
                            @RequestParam double long1,
                            @RequestParam double lat1,
                            @RequestParam(required = false, value = "orderType", defaultValue = "1") Byte orderType,  // add by wg 20190321增加订单类型,默认为用户订单
                            @RequestParam(required = false, value = "transportType", defaultValue = "2") Byte transportType,  // add by wg 20190321增加配送类型，对于同城来说可以选择及时达或同城快送，默认为同城快送  运送方式，0：同城即时达，1：物流,2：同城快送（一般24小时左右送达）
                            @RequestParam(required = false, value = "orderAmount", defaultValue = "0") Integer orderAmount,  // add by wg 20190321增加订单总额，根据订单总额判断是否有满免
                            @RequestParam(required = false, value = "warehouseId") Long warehouseId  // add by wg 20190717增加订单所属仓库
    ) {
        //todo B 端免运费，以后调整
        if (orderType.toString().equals("2")){
            return WrapMapper.ok(0);
        }
        if (warehouseId == null) {
            List<Long> list = new ArrayList<>();
            list.add(shopId);
            List<WmsWarehouseShop> getbyshopid = wmsWarehouseShopService.getbyshopid(list);
            warehouseId = getbyshopid.get(0).getWarehouseId();
        }

        WmsWarehouse byId = wmsWarehouseService.findById(warehouseId);
        Long regionCityId = byId.getRegionCityId();
        if (regionCityId.toString().equals(cityId.toString())) {
            //同城就用及时达，根据距离算
            BigDecimal latitude = byId.getLatitude();
            BigDecimal longitude = byId.getLongitude();
            double latitude2 = latitude.doubleValue();
            double longitude2 = longitude.doubleValue();
            //单位米
            double distance = DistancdUtil.Distance(long1, lat1, longitude2, latitude2);
            System.out.println("距离" + distance);
            WmsTransPrice wmsTransPrice = new WmsTransPrice();
            wmsTransPrice.setWarehouseId(byId.getWarehouseId());
//            wmsTransPrice.setTransportType((byte) 0);
            wmsTransPrice.setTransportType(transportType);  // 同城包括及时达、快送（24小时内到达）两种方式
            wmsTransPrice.setOrderType(orderType);
            List<WmsTransPrice> select = wmsTransPriceService.select(wmsTransPrice);

            // add by wg 20190321
            if (select == null || select.size() <= 0) {
                return WrapMapper.ok(0);
            }

            WmsTransPrice wmsTransPrice1 = select.get(0);

            // add by wg 增加满免
            if (wmsTransPrice1.getIsUpFree() && orderAmount >= wmsTransPrice1.getUpAmount()) {
                return WrapMapper.ok(0);
            }

            Integer first = wmsTransPrice1.getFirst();
            int distance1 = (int) distance;
            if (distance1 <= first) {
                Integer firstPrice = wmsTransPrice1.getFirstPrice();
                return WrapMapper.ok(firstPrice.intValue()); // / 100);
            } else {
                double f1 = new BigDecimal(((float) (distance - wmsTransPrice1.getFirst())) / wmsTransPrice1.getAdditional()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                double v = f1 * wmsTransPrice1.getAdditionalPrice(); // / 100;
                return WrapMapper.ok(wmsTransPrice1.getFirstPrice().intValue() + v); // / 100 + v);
            }
        } else {
            //物流根据重量和省份算
            Example example = new Example(WmsTransPrice.class);
            example.createCriteria().andLike("regionIds", "%" + provinceId + "%").andEqualTo("orderType", orderType)
            .andEqualTo("warehouseId", warehouseId);
            List<WmsTransPrice> select = wmsTransPriceService.selectByExample(example);

            // add by wg 20190321
            if (select == null || select.size() <= 0) {
                return WrapMapper.ok(0);
            }

            WmsTransPrice wmsTransPrice1 = select.get(0);

            // add by wg 增加满免
            if (wmsTransPrice1.getIsUpFree() && orderAmount >= wmsTransPrice1.getUpAmount()) {
                return WrapMapper.ok(0);
            }

            if (weight.intValue() <= wmsTransPrice1.getFirst().intValue()) {
                return WrapMapper.ok(wmsTransPrice1.getFirstPrice()); // / 100);
            } else {
                double f1 = new BigDecimal(((float) (weight - wmsTransPrice1.getFirst())) / wmsTransPrice1.getAdditional()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                double v = f1 * wmsTransPrice1.getAdditionalPrice(); // / 100;
                return WrapMapper.ok(wmsTransPrice1.getFirstPrice().intValue() + v); // / 100 + v);
            }
        }

    }

    //获取运费满免信息
    @GetMapping("/getFreightUpFree")
    public Wrapper<WmsFreightInfo> getFreightUpFree(@RequestParam Long provinceId,
                            @RequestParam Long cityId,
                            @RequestParam Long shopId,
                            @RequestParam(required = false, value = "orderType", defaultValue = "1") Byte orderType,  // add by wg 20190321增加订单类型,默认为店铺订单
                            @RequestParam(required = false, value = "transportType", defaultValue = "2") Byte transportType,  // add by wg 20190321增加配送类型，对于同城来说可以选择及时达或同城快送，默认为同城快送
                            @RequestParam(required = false, value = "warehouseId") Long warehouseId  // add by wg 20190717增加订单所属仓库
    ) {
        List<Long> list = new ArrayList<>();
        list.add(shopId);

        List<WmsWarehouseShop> getbyshopid = wmsWarehouseShopService.getbyshopid(list);
        if (getbyshopid != null && getbyshopid.size() > 0) {

            if (warehouseId == null) {
                warehouseId = getbyshopid.get(0).getWarehouseId();
            }

            WmsWarehouse byId = wmsWarehouseService.findById(warehouseId);
            Long regionCityId = byId.getRegionCityId();
            if (regionCityId.toString().equals(cityId.toString())) {
                WmsTransPrice wmsTransPrice = new WmsTransPrice();
                wmsTransPrice.setWarehouseId(byId.getWarehouseId());
//            wmsTransPrice.setTransportType((byte) 0);
                wmsTransPrice.setTransportType(transportType);  // 同城包括及时达、快送（24小时内到达）两种方式
                wmsTransPrice.setOrderType(orderType);
                List<WmsTransPrice> select = wmsTransPriceService.select(wmsTransPrice);

                // add by wg 20190321
                if (select == null || select.size() <= 0) {
                    return WrapMapper.ok(null);
                }

                WmsTransPrice wmsTransPrice1 = select.get(0);

                WmsFreightInfo wmsFreightInfo = new WmsFreightInfo();
                wmsFreightInfo.setIsUpFree(wmsTransPrice1.getIsUpFree());
                wmsFreightInfo.setUpAmount(wmsTransPrice1.getUpAmount());

                return WrapMapper.ok(wmsFreightInfo);
            } else {
                //物流根据重量和省份算
                Example example = new Example(WmsTransPrice.class);
                Example.Criteria criteria = example.createCriteria();

                criteria.andLike("regionIds", "%" + provinceId + "%");
                criteria.andEqualTo("orderType", orderType);
                if (warehouseId != null) {
                    criteria.andEqualTo("warehouseId", warehouseId);
                }

                List<WmsTransPrice> select = wmsTransPriceService.selectByExample(example);

                // add by wg 20190321
                if (select == null || select.size() <= 0) {
                    return WrapMapper.ok(null);
                }

                WmsTransPrice wmsTransPrice1 = select.get(0);
                WmsFreightInfo wmsFreightInfo = new WmsFreightInfo();
                wmsFreightInfo.setIsUpFree(wmsTransPrice1.getIsUpFree());
                wmsFreightInfo.setUpAmount(wmsTransPrice1.getUpAmount());

                return WrapMapper.ok(wmsFreightInfo);
            }
        } else {
            return WrapMapper.ok(null);
        }
    }
}
